﻿using System;
using System.Windows.Input;
using GurLoader.Util;

namespace GurLoader.View
{
    public class RelayCommand<T> : ICommand where T : class
    {
        #region Fields 

        public Action<T> CommandAction { get; set; }
        public Func<T,bool> CanExecuteFunc { get; set; }

        #endregion // Fields 

        #region Constructors 

        private IRequeryable Requeryable { get; set; }

        public RelayCommand() : this(new CommandManagerWrapper())
        {
            
        }

        public RelayCommand(IRequeryable requeryable)
        {
            Requeryable = requeryable;
        }

        #endregion // Constructors 

        #region ICommand Members 

        public bool CanExecute(object parameter)
        {
            T t = parameter as T;
            return CanExecuteFunc == null || CanExecuteFunc(t);
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                Requeryable.RequerySuggested += value;
            }

            remove
            {
                Requeryable.RequerySuggested -= value;
            }
        }

        public void Execute(object parameter)
        {
            T t = parameter as T;
            CommandAction(t);
        }

        #endregion // ICommand Members
    }
}